package org.gldap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;


import org.apache.log4j.Logger;

public class ConfFile {
	private static Logger log4j = Logger.getLogger(ConfFile.class);
	private String theFileContents;
	private String theFile = System.getProperty("user.dir")+ File.separator + "gldap.conf";
	public static void main ( String[] args ) throws IOException{
		ConfFile a = new ConfFile();
		log4j.warn(a.getConfigrationAttribure("email") );
	}
	
	
	
	public ConfFile() throws IOException {
		log4j.debug("ConfFile instantiated with configuration file: " + theFile );
		theFileContents = readTextFile( theFile );
	}
	
	private String readTextFile(String _filename) throws IOException {
		String s = "";
		try {
			BufferedReader in = new BufferedReader(new FileReader(_filename));
			String str;
			while ((str = in.readLine()) != null) {
				s = s + "=" + str;
			}
			in.close();
		} catch (IOException e) {
			log4j.error("Configuration file: " + theFile + " inaccessible");
			log4j.error(e.getMessage());
			throw e;
		}
		return (s);
	}
	
	
	public String getConfigrationAttribure( String _key ){
		log4j.debug("attempting to retrieve: " + _key + " from configuration file");
	     StringTokenizer st = new StringTokenizer(this.theFileContents , "=");
	     while (st.hasMoreTokens()) {
	    		String s = st.nextToken();
				if (s.equals(_key)) {
					log4j.debug("key: " + _key  + " retrieved successfully from  configuration file");
					return (st.nextToken());
				}
	     }
	     log4j.error("key: " + _key + "retrieval from configuration filed FAILED");
		return null;	
	}
}
